<?php
namespace App\Http\Controllers\Client\Activity;

use App\Http\Controllers\ClientController;
use App\Models\Shop;
use App\Models\WechatPay;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LotteryBuyController extends ClientController
{
    /**
     * @api {post} /api/client/activity/lottery/buy 创建购买霸王餐订单
     *
     * @apiVersion 0.1.0
     * @apiName 购买霸王餐
     * @apiGroup course
     * @apiDescription 创建购买霸王餐订单
     *
     * @apiParam {Number} num     购买数量 （必填）
     * @apiParam {Number} price       单价    （必填）
     * @apiParam {Number} st_id       店铺类型id（必填）
     *
     * @apiSuccess {int}      code  接口返回正误标志,0为成功,其他为失败.
     * @apiSuccess {String}   msg   接口返回信息
     * @apiSuccess {Object[]} data  接口返回data.
     *
     * @apiSuccessExample {json} Success-Response:
     *     {
     *       "code": 0,
     *       "msg": "创建成功"
     *       "data": [...]
     *     }
     */
    public function index()
    {
        $all = $this->all;
        try{
            // 验证参数
            if(!isset($all['num'])){
                throw new \Exception('缺少参数:num');
            }
            if(!isset($all['price'])){
                throw new \Exception('缺少参数:price');
            }
            if(!isset($all['st_id'])){
                throw new \Exception('缺少参数:st_id');
            }
            // 检查价格是否有变化
            $price = DB::table('shop_type')
                ->where('st_id','=',$all['st_id'])
                ->value('lottery_price');
            if($price != $all['price']){
                return $this->setReturnJson(-1,'价格有变化，请刷新当前页面重试');
            }

            // 检查是否有符合条件的店铺
            if(!Shop::verified($this->we_id)){
                return $this->setReturnJson(-1,'您当前没有审核通过的店铺，请重新编辑店铺并等待管理员审核后再购买');
            }

            // 实例化微信支付订单类
            $pay = new WechatPay(
                $this->we_id,
                $this->openid,
                4,
                $all['st_id'],
                $all['num']
            );

        }catch (\Exception $e){
            Log::error(LotteryBuyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'订单生成失败');
        }

        // 生成订单
        try{
            DB::beginTransaction();

            // 查询业务信息
            $order_message = $pay->getOrderMessage();
            // 创建系统订单
            $message = $pay->createOrder($order_message);
            switch ($message){
                case 7:
                    DB::commit();
                    return $this->setReturnJson(-1,'订单已支付完成，请刷新重试');
                    break;
            }
            // 创建微信订单
            $prepay_id = $pay->createWechatOrder($message);
            // 返回微信请求
            $result = $pay->sdkConfig($prepay_id);

            DB::commit();
            return $this->setReturnJson(0,'订单生成成功',$result);

        }catch (\Exception $e){
            DB::rollBack();
            Log::error(LotteryBuyController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'订单生成失败');
        }

    }

}
